﻿using EasyShop.UserService.App.Interface;
using EasyShop.UserService.Repository.Domain;
using EasyShop.UserService.Request;
using EasyShop.UserService.Response;
using Infrastructure;
using System;
using System.Linq;

namespace EasyShop.UserService.App
{
    public class UserApp:IUserApp
    {
        private readonly MySqlDBContext _mySqlDBContext;
        public UserApp(MySqlDBContext mySqlDBContext)
        {
            _mySqlDBContext = mySqlDBContext;
        }
        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public UserView Get(string id)
        {
            var user = _mySqlDBContext.User.Where(c => c.Id == id).FirstOrDefault();
            var userView = user.MapTo<UserView>();
            return userView;
        }
        /// <summary>
        /// 注册接口
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public string Register(UserRegisterReq request)
        {
            var result = string.Empty;
            var exists = _mySqlDBContext.User.Where(c => c.UserName == request.UserName).FirstOrDefault();
            if (exists == null)
            {
                var user = new User()
                {
                    Id = Guid.NewGuid().ToString(),
                    UserName = request.UserName,
                    Password = request.Password,
                    CreateTime = DateTime.Now,
                };
                _mySqlDBContext.User.Add(user);
                _mySqlDBContext.SaveChanges();
                result = "注册成功";
            }
            else
            {
                result = "名称已存在，换一个试试。"; 
            }
            return result;
        }
    }
}
